#!/bin/bash

# 获取当前脚本所在路径
BASEPATH=$(cd "$(dirname $0)" || exit; pwd)

# 配置 MindSpore 文件及下载地址
MINDSPORE_FILE_NAME="mindspore-lite-2.4.1-linux-aarch64"
MINDSPORE_FILE="${MINDSPORE_FILE_NAME}.tar.gz"
MINDSPORE_LITE_DOWNLOAD_URL="https://ms-release.obs.cn-north-4.myhuaweicloud.com/2.4.1/MindSpore/lite/release/linux/aarch64/mindspore-lite-2.4.1-linux-aarch64.tar.gz"

# 创建构建、库、头文件目录
mkdir -p build    # cmake 产物目录
mkdir -p lib      # 动态库目录
mkdir -p include  # 头文件目录

# 如果 MindSpore 文件不存在，则从网络下载
if [ ! -e ${BASEPATH}/build/${MINDSPORE_FILE} ]; then
  echo "下载 MindSpore 文件..."
  wget -c -O ${BASEPATH}/build/${MINDSPORE_FILE} ${MINDSPORE_LITE_DOWNLOAD_URL}
fi

# 解压下载的文件，如果已解压则跳过
if [ ! -d ${BASEPATH}/build/${MINDSPORE_FILE_NAME} ]; then
  echo "解压 MindSpore 文件..."
  tar -zxvf ${BASEPATH}/build/${MINDSPORE_FILE} -C ${BASEPATH}/build/
else
  echo "MindSpore 文件已解压，跳过解压步骤"
fi

# 拷贝必要的库文件到 lib 目录，如果已存在则跳过
if [ ! -f ${BASEPATH}/lib/libmindspore-lite.so ]; then
  echo "拷贝 libmindspore-lite.so 到 lib 目录..."
  cp -r ${BASEPATH}/build/${MINDSPORE_FILE_NAME}/runtime/lib/libmindspore-lite.so ${BASEPATH}/lib
else
  echo "libmindspore-lite.so 已存在，跳过拷贝"
fi

if [ ! -f ${BASEPATH}/lib/libmindspore_glog.so.0 ]; then
  echo "拷贝 libmindspore_glog.so.0 到 lib 目录..."
  cp -r ${BASEPATH}/build/${MINDSPORE_FILE_NAME}/runtime/third_party/glog/libmindspore_glog.so.0* ${BASEPATH}/lib/libmindspore_glog.so.0
else
  echo "libmindspore_glog.so.0 已存在，跳过拷贝"
fi

# 创建软连接，如果软连接已存在则跳过
if [ ! -L ${BASEPATH}/lib/libmindspore_glog.so ]; then
  echo "创建 libmindspore_glog.so 软连接..."
  ln -s ${BASEPATH}/lib/libmindspore_glog.so.0 ${BASEPATH}/lib/libmindspore_glog.so
else
  echo "libmindspore_glog.so 软连接已存在，跳过创建"
fi

# 拷贝头文件到 include 目录，如果 include 目录不为空则跳过
if [ "$(ls -A ${BASEPATH}/include)" ]; then
  echo "include 目录不为空，跳过拷贝头文件"
else
  echo "拷贝头文件到 include 目录..."
  cp -r ${BASEPATH}/build/${MINDSPORE_FILE_NAME}/runtime/include ${BASEPATH}/include
fi

# 进入构建目录并执行 cmake 配置与编译
cd ${BASEPATH}/build || exit
cmake -DCMAKE_TOOLCHAIN_FILE=${BASEPATH}/toolchain.cmake ..
make

# 编译产物
mkdir -p ${BASEPATH}/bin
cp ${BASEPATH}/build/mindspore_mnist_demo  ${BASEPATH}/bin
echo "产物目录：${BASEPATH}/mindspore_mnist_demo/"
echo "执行示例: ./bin/mindspore_mnist_demo ./model/mnist.ms"

# 返回到脚本所在目录
cd ${BASEPATH}/build || exit
